<?php
/*
* Class teia\webdev\php\core\Settings
* Core class for web site settings
*
* @author Bernardo Quibiana
* @date created: 20111127
*
* @date modified: 20111127
* @modified: Bernardo Quibiana
*/

// namespace declaration: Abstract Data Types
namespace teia\webdev\php\core;

require_once 'MySqlLink.inc';
require_once 'IYamlItem.inc';
require_once 'SettingItem.inc';
require_once 'TypePool.inc';

final class Settings {
	private $conf_data;
	
	private static $_settings = null;
	
	// persistency: context, object, field, value
	private function __construct($setting_items) {
		$this->conf_data = array();
		$this->load_from_array($setting_items);
	}
	
	static function settings($db_tb='conf_settings') {
		if (is_null(self::$_settings)) {
			$setting_items = SettingItem::db_factory(null, 0, $db_tb);
			self::$_settings = new Settings($setting_items);
		}
		return self::$_settings;
	}
	
	private function load_from_array($setting_items) {
		foreach ($setting_items as $it) {
			$ctxt = $it->get('context');
			$obj = $it->get('object');
			$fld = $it->get('field');
			$val = $it->get('value');
			
			if (!isset($this->conf_data[$ctxt]) || is_null($this->conf_data[$ctxt])) {
				$this->conf_data[$ctxt] = array();
			}
			if (!isset($this->conf_data[$ctxt][$obj]) || is_null($this->conf_data[$ctxt][$obj])) {
				$this->conf_data[$ctxt][$obj] = array();
			}
			$this->conf_data[$ctxt][$obj][$fld] = $val;
		}
	}

	private function load_from_file($path, $model=DataModel::YAML) {
		switch ($model) {
			case DataModel::YAML:
				$data = yaml_parse_file($path);
				if (is_array($data)) {
					$this->conf_data = $data;
				} else {
					throw new \UnexpectedValueException("Invalid data parsed from YAML file '$path'", 999, null);
				}
			break;
			default:
				;
			break;
		}
	}
	
	private function load_from_yaml($yaml) {
		$this->conf_data = yaml_parse($yaml);
	}
	
	public function save_to_file($path, $model=DataModel::YAML) {
		switch ($model) {
			case DataModel::YAML:
				return yaml_emit_file($path, $this->conf_data, YAML_UTF8_ENCODING);
			default:
				;
			break;
		}
	}
	
	public function get_yaml() {
		return yaml_emit($this->conf_data);
	}
	
	public function get_conf_data($ctxt, $obj, $fld) {
		return isset($this->conf_data[$ctxt][$obj][$fld]) ? $this->conf_data[$ctxt][$obj][$fld] : null;
	}
}
